'use strict';

const Fs = require('fs');
const Path = require('path');
const Service = require('egg').Service;

class ECSService extends Service {

  /**
   * 根据路径获取相应的文件
   * @param {*} path 路径
   */
  getFilesWithPath(path) {
    const fileNames = Fs.readdirSync(path);
    return fileNames.map(item => {
      const filePath = Path.join(path, item);
      const files = Fs.statSync(filePath);
      const isDir = files.isDirectory();
      const relativePaths = filePath.split('public/up-image/');
      return {
        title: item,
        isDir,
        filePath: relativePaths[1],
        children: isDir ? this.getFilesWithPath(filePath) : null,
      };
    });
  }

  /**
   * 获取所有文件
   */
  allFiles() {
    const imagePath = Path.resolve(__dirname, '../public/up-image/');
    const data = this.getFilesWithPath(imagePath);
    return data;
  }

  /**
   * 删除指定路径的文件、文件夹
   */
  deleteFile() {
    const path = Path.resolve(__dirname, '../public/up-image/', this.ctx.query.path);
    this.deleteFileWithPath(path);
  }

  /**
   * 删除所有文件或者文件夹
   */
  deleteAll() {
    const path = Path.resolve(__dirname, '../public/up-image/');
    this.deleteFileWithPath(path, false);
  }

  /**
   * 根据路径删除指定文件夹、文件
   * @param {*} path 路径
   * @param {*} removeRootDir 是否删除跟文件夹
   */
  deleteFileWithPath(path, removeRootDir = true) {
    const files = Fs.statSync(path);
    const isDir = files.isDirectory();
    if (isDir) {
      const fileNames = Fs.readdirSync(path);
      fileNames.forEach(item => {
        const filePath = Path.join(path, item);
        this.deleteFileWithPath(filePath);
      });
      // 删除文件夹
      if (removeRootDir) {
        Fs.rmdirSync(path);
      }
    } else {
      Fs.unlinkSync(path);
    }
  }
}

module.exports = ECSService;
